<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/15
 * Time: 20:15
 * @link http://www.lmterp.cn
 */

namespace app\common\service\product;

use app\common\library\Tools;
use app\common\model\ProductCategory;
use app\common\model\Orders;
use app\common\model\Producer;
use app\common\model\Product;
use app\common\model\ProductAttr;
use app\common\model\ProductBrand;
use app\common\model\ProductImage;
use app\common\model\ProductKeyword;
use app\common\model\ProductKeywordCategory;
use app\common\model\ProductPurchase;
use app\common\model\ProductSpec;
use app\common\model\ProductStore;
use app\common\model\ProductUnit;
use app\common\model\WarehouseStock;
use app\common\service\BaseService;
use Env;
use Exception;
use think\Db;
use think\exception\DbException;
use think\facade\Log;

class ProductService extends BaseService
{
    /**
     * 添加产品
     * @param array $productData 产品数据
     * @return Product|bool
     * @date 2020/09/05
     * @author longli
     */
    public function addProduct($productData = [])
    {
        try
        {
            Db::startTrans();
            $pData = Product::getFilterField($productData['product'], '');
            if(empty($pData)) return false;
            $pData = Tools::trim($pData);
            if(empty($pData['image_url']) && !empty($productData['image']['images'])) $pData['image_url'] = current($productData['image']['images']);
            if(isset($pData['product_id'])) $product = Product::get($pData['product_id']);
            if(!empty($product))
            {
                $product->save($pData);
            }
            else
            {
                $product = Product::create($pData)->refresh();
            }
            if(!empty($productData['store']))
            {
                $this->addStore($product, $productData['store']);
                if(!empty($productData['stock']['warehouse_id']))
                {
                    if(!empty($productData['stock']['stock']))
                        $productData['stock']['stock'] = Tools::replaceArrayKey($productData['store']['sku'], $productData['stock']['stock']);
                    $this->addStock($product, $productData['stock']);
                }
            }
            if(!empty($productData['image'])) $this->addImages($product, $productData['image']['images']);
            if(!empty($productData['producer'])) $this->addProductPurchase($product, $productData['producer']);
            if(!empty($productData['attr'])) $this->addAttr($product, $productData['attr']['values']);
            Db::commit();
            return $product;
        }catch(DbException $exception)
        {
            Db::rollback();
            Log::info(sprintf("产品录入失败，错误信息【%s】", $exception->getMessage()));
            return false;
        }
    }

    /**
     * 添加产品详情
     * @param Product $product 产品
     * @param array $storeData 产品详情
     * @date 2020/09/05
     * @author longli
     */
    public function addStore(Product $product, $storeData = [])
    {
        if(!isset($storeData[0])) $storeData = $this->transformToArray($storeData);
        $ndids = [];
        foreach($storeData as $item)
        {
            $data = ProductStore::getFilterField($item, '');
            if(empty($data)) continue;
            $data = Tools::trim($data);
            $store = null;
            if(isset($data['store_id'])) $store = ProductStore::get($data['store_id']);
            if(empty($store) && !empty($data['sku'])) $store = ProductStore::get(['sku' => $data['sku']]);
            if(empty($data['image_url'])) $data['image_url'] = !empty($product->image_url) ? $product->image_url : '';
            $data['product_id'] = $product->product_id;
            if(!empty($store))
            {
                $store->save($data);
            }
            else
            {
                $store = ProductStore::create($data);
            }
            $ndids[] = $store->store_id;
        }
        // 删除变体
        ProductStore::destroy(function($query) use($product, $ndids)
        {
            $query->where('product_id', 'eq', $product->product_id);
            if(!empty($ndids)) $query->where('store_id', 'not in', $ndids);
        });
    }

    /**
     * 录入商品初始化库存信息
     * @param Product $product 商品信息
     * @param array $stockData 库存信息
     * @date 2020/09/16
     * @author longli
     */
    protected function addStock(Product $product, $stockData = [])
    {
        if(!isset($stockData['warehouse_id']))return;
        foreach($stockData['warehouse_id'] as $w)
        {
            foreach($product->stores as $store)
            {
                if(WarehouseStock::hasSku($w, $store->sku)) continue;
                $qty = !isset($stockData['stock'][$store->sku]) || $stockData['stock'][$store->sku] < 1 ? 0 : intval($stockData['stock'][$store->sku]);
                $data = [
                    'store_id'     => $store->store_id,
                    'warehouse_id' => $w,
                    'sku'          => $store->sku,
                    'stock'        => $qty,
                ];
                WarehouseService::getInstance()->addStock($store->store_id, $data);
            }
        }
    }

    /**
     * 添加商品采购信息
     * @param Product $product 产品
     * @param array $purchase 采购信息
     * @date 2020/09/05
     * @author longli
     */
    public function addProductPurchase(Product $product, $purchase = [])
    {
        if(!isset($purchase[0])) $purchase = $this->transformToArray($purchase);
        $ndppId = [];
        $isOne = count($purchase) == 1;
        foreach($purchase as $item)
        {
            $data = ProductPurchase::getFilterField($item, '');
            if(empty($data)) continue;
            $data = Tools::trim($data);
            $data['product_id'] = $product->product_id;
            $data['is_default'] = !empty($data['is_default']) ? ProductPurchase::IS_YES : ProductPurchase::IS_NO;
            $data['status'] = !empty($data['status']) ? ProductPurchase::IS_YES : ProductPurchase::IS_NO;
            if(!empty($data['producer_id']) && $producer = Producer::get($data['producer_id'])) $data['producer_name'] = $producer->name;
            if(isset($data['pp_id']) && $purchaseObj = ProductPurchase::get($data['pp_id']))
            {
                $purchaseObj->save($data);
            }
            else
            {
                $purchaseObj = ProductPurchase::create($data)->refresh();
            }
            $ndppId[] = $purchaseObj->pp_id;
            if($isOne || !empty($data['is_default']))
            {
                $product->default_purchase = $purchaseObj->producer_name;
                $product->price = $purchaseObj->price;
                $product->save();
            }
        }
        // 删除商品采购信息
        ProductPurchase::destroy(function($query) use($product, $ndppId)
        {
            $query->where('product_id', 'eq', $product->product_id);
            if(!empty($ndppId)) $query->where('pp_id', 'not in', $ndppId);
        });
    }

    /**
     * 添加图片
     * @param Product $product 产品
     * @param string|string[] $images 图片
     * @date 2020/09/05
     * @author longli
     */
    public function addImages(Product $product, $images = [])
    {
        if(!is_array($images)) $images = explode(',', $images);
        $images = Tools::trim($images);
        try
        {
            foreach (ProductImage::where(['product_id' => $product->product_id])->select() as $item)
            {
                if(!in_array($item->image_url, $images)) $item->delete();
            }
        }catch(Exception $e){}
        foreach($images as $image)
        {
            if(ProductImage::where(['image_url' => $image, 'product_id' => $product->product_id])->count()) continue;
            $data = [
                'image_url' => $image,
                'product_id' => $product->product_id,
            ];
            if($info = Tools::getImageInfo(Env::get("root_path") . "public{$image}")) $data += $info;
            ProductImage::create($data);
        }
    }

    /**
     * 添加属性
     * @param Product $product 产品详情
     * @param int|int[] $attrs 属性
     * @date 2020/09/05
     * @author longli
     */
    public function addAttr($product, $attrs = [])
    {
        if(!is_array($attrs)) $attrs = explode(',', $attrs);
        try
        {
            foreach (ProductAttr::where(['product_id' => $product->product_id])->select() as $item)
            {
                if(!in_array($item->spec_id, $attrs)) $item->delete();
            }
        }catch(Exception $e){}
        foreach($attrs as $attr)
        {
            $attrObj = ProductAttr::get(['product_id' => $product->product_id, 'spec_id' => $attr]);
            $data = [
                'spec_id' => $attr,
                'product_id' => $product->product_id
            ];
            if($spce = ProductSpec::get($attr))
            {
                $data += [
                    'name' => $spce->name,
                    'value' => $spce->value,
                ];
            }
            !empty($attrObj) ? $attrObj->save($data) : ProductAttr::create($data);
        }
    }

    /**
     * 解析表单请求数据
     * @param array $data 请求数据
     * @param bool $prefix 是否保留前缀，默认不保留
     * @return array
     * @date 2020/09/09
     * @author longli
     */
    public function parseRequestData($data = [], $prefix = false)
    {
        $ret = ['other' => []];
        foreach($data as $k => $v)
        {
            $temp = explode('.', $k);
            if(count($temp) == 2)
            {
                $pre = $temp[0];
                if(!isset($ret[$pre])) $ret[$pre] = [];
                if($pre == 'image' && !is_array($v)) $v = explode(',', $v);
                $tk = $prefix ? $k : $temp[1];
                $ret[$pre] += [$tk => $v];
            }
            else
            {
                $ret['other'] += [$k => $v];
            }
        }
        return $ret;
    }

    /**
     * 将复合表单转换为二维数组
     * @param array $formData
     * @return array
     * @date 2021/06/16
     * @author longli
     */
    public function transformToArray($formData = [])
    {
        $ret = [];
        $keys = array_keys($formData);
        foreach($formData[$keys[0]] as $key => $item)
        {
            $temp = [];
            foreach($keys as $k)
            {
                $temp[$k] = isset($formData[$k][$key]) ? $formData[$k][$key] : '';
            }
            $ret[] = $temp;
        }
        return $ret;
    }

    /**
     * 删除产品
     * @param int|int[] $ids 产品id
     * @return bool
     * @date 2020/09/05
     * @author longli
     */
    public function deleteProductById($ids)
    {
        try
        {
            Db::startTrans();
            Product::destroy($ids);
            ProductImage::destroy(function($query)use($ids){$query->where("product_id", "in", $ids);});
            ProductStore::destroy(function($query)use($ids){$query->where("product_id", "in", $ids);});
            ProductAttr::destroy(function($query)use($ids){$query->where("product_id", "in", $ids);});
            ProductPurchase::destroy(function($query)use($ids){$query->where("product_id", "in", $ids);});
            Db::commit();
            return true;
        }catch(DbException $exception)
        {
            Db::rollback();
            Log::info(sprintf("商品删除失败，提示信息【%s】", $exception->getMessage()));
        }
        return false;
    }

    /**
     * 获取 sku 总重量，单位(g)
     * @param array $skus
     * @return float
     * @date 2020/09/05
     * @example $skus = [
     *      'A001' => 2,
     *      'A002' => 1,
     * ];
     * @author longli
     */
    public function getTotalWeight($skus = [])
    {
        $weight = 0;
        try
        {
            foreach(ProductStore::field(["sku", "weight"])->where("sku", "in", array_keys($skus))->select() as $store)
            {
                if($store->weight > 0) $weight += $store->weight * $skus[$store->sku];
            }
        }catch(Exception $e){}
        return $weight;
    }

    /**
     * 生成内部同类sku
     * @param int $num 生成多少个，默认1个, 同类sku最大700个
     * @param string $prefix SKU前缀
     * @param int $len sku 位数默认，8位
     * @return string|string[]
     * @date 2020/09/09
     * @author longli
     */
    public function generateSameSku($num = 1, $prefix = '', $len = 8)
    {
        if($num < 1 || $num > 700) return [];
        $sku = $prefix ?: $this->generateSku(1, $len);
        if($num == 1) return $sku;
        $ret = [];
        $prefix = $suffix = "";
        $base = 65;
        $p = 0;
        for($i = 0; $i < $num; $i++)
        {
            if($i > 25 && $i % 26 == 0) $prefix = chr($base + $p++);
            $t = $i < 26 ? $i : $i % 26;
            $suffix = $prefix . chr($base + $t);
            $ret[] = $sku . "-{$suffix}";
        }
        return $ret;
    }

    /**
     * 添加相同 sku
     * @param string $sku sku
     * @param int $num 要添加的数量，默认为1个, 同类sku最大700个
     * @return string|string[]
     * @date 2020/09/10
     * @author longli
     */
    public function addSameSku($sku, $num = 1)
    {
        if($num < 1 || $num > 700) return [];
        $tsku = explode('-', $sku)[0];
        $psku = ProductStore::where("sku", "like", "$tsku%")->order(Db::raw("LENGTH(sku) desc,sku desc"))->value("sku");
        if(empty($psku)) return "";
        $prefix = $suffix = '';
        $temp = explode('-', $psku);
        $sku = $temp[0];
        if(count($temp) > 1)
        {
           if(strlen($temp[1]) > 1)
           {
               $prefix = $temp[1][0];
               $suffix = $temp[1][1];
           }
           else
           {
               $suffix = $temp[1];
           }
        }
        $ret = [];
        for($i = 0; $i < $num; $i++)
        {
            $suffix = ord($suffix) + 1;
            if($suffix > 90)
            {
                $suffix = 65;
                $p = !empty($prefix) ? ord($prefix) + 1 : 65;
                $prefix = chr($p);
            }
            $suffix = chr($suffix);
            $ret[] = $sku . "-{$prefix}{$suffix}";
        }
        if($num == 1) return $ret[0];
        return $ret;
    }

    /**
     * 生成内部 sku
     * @param int $num 生成多少个，默认1个
     * @param int $len sku 位数默认，8位
     * @return string|string[]
     * @date 2020/09/09
     * @author longli
     */
    public function generateSku($num = 1, $len = 8)
    {
        if($num < 1) return [];
        $ret = [];
        for($i = 0; $i < $num; $i++)
        {
            do
            {
                $sku = strtoupper(Tools::getRandStr($len, 2));
            }while(in_array($sku, $ret) || ProductStore::where(['sku' => $sku])->count());
            $ret[] = $sku;
        }
        if($num == 1) return $ret[0];
        return $ret;
    }

    /**
     * 添加商品分类
     * @param array $data 分类信息
     * @return ProductCategory|bool
     * @date 2020/09/18
     * @author longli
     */
    public function addCategory($data = [])
    {
        $cDate = ProductCategory::getFilterField($data, '');
        if(empty($cDate)) return false;
        $cDate = Tools::trim($cDate);
        $cate = null;
        if(isset($cDate['cate_id'])) $cate = ProductCategory::get($cDate['cate_id']);
        if(!empty($cate))
        {
            $cate->save($cDate);
        }
        else
        {
            $cate = ProductCategory::create($cDate)->refresh();
        }
        return $cate;
    }

    /**
     * 添加关键词分类
     * @param array $data 分类信息
     * @return ProductKeywordCategory|bool
     * @date 2020/09/18
     * @author longli
     */
    public function addKeywordCategory($data = [])
    {
        $cDate = ProductKeywordCategory::getFilterField($data, '');
        if(empty($cDate)) return false;
        $cDate = Tools::trim($cDate);
        $cate = null;
        if(isset($cDate['cate_id'])) $cate = ProductKeywordCategory::get($cDate['cate_id']);
        if(!empty($cate))
        {
            $cate->save($cDate);
        }
        else
        {
            $cate = ProductKeywordCategory::create($cDate)->refresh();
        }
        return $cate;
    }

    /**
     * 添加关键词
     * @param array $data 关键词信息
     * @return ProductKeyword|false
     * @date 2021/07/20
     * @author longli
     */
    public function addKeyword($data = [])
    {
        $kData = ProductKeyword::getFilterField($data, '');
        if(empty($kData)) return false;
        $kData = Tools::trim($kData);
        $keyword = null;
        if(isset($kData['word_id'])) $keyword = ProductKeyword::get($kData['word_id']);
        else if(isset($kData['word'])) $keyword = ProductKeyword::get(['word' => $kData['word']]);

        if(!empty($keyword))
        {
            $keyword->save($kData);
        }
        else
        {
            $keyword = ProductKeyword::create($kData)->refresh();
        }
        return $keyword;
    }

    /**
     * 添加规格
     * @param array $data 规格信息
     * @return ProductSpec|bool
     * @date 2020/09/18
     * @author longli
     */
    public function addSpec($data = [])
    {
        $sData = ProductSpec::getFilterField($data, '');
        if(empty($sData)) return false;
        $sData = Tools::trim($sData);
        $spec = null;
        if(isset($sData['spec_id'])) $spec = ProductSpec::get($sData['spec_id']);
        if(!empty($spec))
        {
            $spec->save($sData);
        }
        else
        {
            $spec = ProductSpec::create($sData)->refresh();
        }
        return $spec;
    }

    /**
     * 添加计量单位
     * @param array $data 计量单位信息
     * @return ProductUnit|bool
     * @date 2020/09/18
     * @author longli
     */
    public function addUnit($data = [])
    {
        $uData = ProductUnit::getFilterField($data, '');
        if(empty($uData)) return false;
        $uData = Tools::trim($uData);
        $unit = null;
        if(isset($uData['unit_id'])) $unit = ProductUnit::get($uData['unit_id']);
        if(!empty($unit))
        {
            $unit->save($uData);
        }
        else
        {
            $unit = ProductUnit::create($uData)->refresh();
        }
        return $unit;
    }

    /**
     * 添加品牌
     * @param array $data 品牌信息
     * @return ProductBrand|bool
     * @date 2020/09/18
     * @author longli
     */
    public function addBrand($data = [])
    {
        $bData = ProductBrand::getFilterField($data, '');
        if(empty($bData)) return false;
        $bData = Tools::trim($bData);
        $brand = null;
        if(isset($bData['brand_id'])) $brand = ProductBrand::get($bData['brand_id']);
        if(!empty($brand))
        {
            $brand->save($bData);
        }
        else
        {
            $brand = ProductBrand::create($bData)->refresh();
        }
        return $brand;
    }

    /**
     * 检查 SKU 是否属于当前供应商
     * @param int $producerId 供应商 id
     * @param string|int $sku 商品SKU 或者变体ID
     * @return bool
     * @date 2020/12/19
     * @author longli
     */
    public function checkProSku($producerId, $sku = '')
    {
        $sku = trim($sku);
        if(!($store = ProductStore::field(['product_id'])->where("store_id", $sku)->whereOr("sku", $sku)->find())) return false;
        return !!ProductPurchase::where([
            "producer_id" => $producerId,
            "product_id" => $store->product_id,
        ])->count();
    }

    /**
     * 批量检查 SKU 是否当前供应商
     * @param int $producerId 供应商 ID
     * @param array $skus sku 列表
     * @return bool|string
     * @date 2020/12/19
     * @author longli
     */
    public function batchCheckSku($producerId, $skus = [])
    {
        if(!is_array($skus)) $skus = explode(',', $skus);
        foreach($skus as $sku)
        {
            if(!$this->checkProSku($producerId, $sku)) return $sku;
        }
        return true;
    }

    /**
     * 检查 SKU 列表是否为同一个供应商
     * @param array $skus sku 列表
     * @return bool|array false 为不在同一个供应商，array 为可以生产的供应商id
     * @date 2020/12/19
     * @author longli
     */
    public function checkSkuOfProducer($skus = [])
    {
        if(empty($skus)) return false;
        if(is_string($skus)) $skus = explode(',', $skus);
        if(count($skus) == 1) return true;
        $stores = ProductStore::alias("s")
            ->join(ProductPurchase::getTable() . " p", "p.product_id=s.product_id")
            ->whereIn("s.sku", $skus)
            ->field(["p.producer_id", "s.sku"])
            ->select();
        $temp = [];
        foreach($stores as $store)
        {
            if(isset($temp[$store['sku']]))
            {
                $temp[$store['sku']][] = $store['producer_id'];
            }
            else
            {
                $temp[$store['sku']] = [$store['producer_id']];
            }
        }
        $temp = array_values($temp);
        $next = null;
        for($i = 0; $i < count($temp); $i++)
        {
            if($next === null)
            {
                $next = $temp[$i];
                $i++;
            }
            $next = array_intersect($next, $temp[$i]);
            if(empty($next)) return false;
        }
        return $next;
    }

    /**
     * 生成二维码
     * @param string $text 二维码字符
     * @param string $logoPath log 路径
     * @param bool $isFile 是否生成文件，默认生成文件
     * @return string 为不在同一个供应商，array 为可以生产的供应商id
     * @date 2020/12/24
     * @author longli
     */
    public function generateQrCode($text, $logoPath = '', $isFile = true)
    {
        $qrCode = new \Endroid\QrCode\QrCode($text);
        if(!empty($logoPath) && is_file($logoPath))
        {
            $qrCode->setLogoSize(40, 40);
            $qrCode->setLogoPath($logoPath);
        }
        if(!$isFile)
        {
            header('Content-Type: '.$qrCode->getContentType());
            echo $qrCode->writeString();
            die;
        }
        $path = \think\facade\Config::get("qrcode");
        $fileName = Tools::getRandStr(16) . ".png";
        if(!is_dir($path)) mkdir($path, 0777, true);
        $absName = "{$path}{$fileName}";
        $qrCode->writeFile($absName);
        return self::hiddenRootPath($absName);
    }

    /**
     * 识别二维码内容
     * @param string $path 二维码路径
     * @return string 成功返回识别内容，失败返回空字符串
     * @date 2020/12/24
     * @author longli
     */
    public function readQrCode($path = '')
    {
        if(Tools::startWith($path, '/attachment')) $path = \Env::get('root_path') . "./public{$path}";
        if(!is_file($path)) return "";
        $qrReader = new \Zxing\QrReader($path);
        if($text =  $qrReader->text()) return $text;
        return "";
    }

    /**
     * 生成一维码
     * @param string $text 一维码字符
     * @return string 返回HTML，或者图片路径
     * @date 2020/12/24
     * @author longli
     */
    public function generateBarCode($text, $config = [])
    {
        $barType = \Picqer\Barcode\BarcodeGenerator::TYPE_CODE_128;
        $width = isset($config['width']) && is_numeric($config['width']) ? abs($config['width']) : 2;
        $height = isset($config['height']) && is_numeric($config['height']) ? abs($config['height']) : 50;
        $barColor = isset($config['color']) ? $config['color'] : [0, 0, 0];
        $showText = isset($config['show_text']) && $config['show_text'];
        $isHtml = isset($config['is_html']) && $config['is_html'];
        $replace = !isset($config['replace']) || $config['replace'];
        // 如果是 HTML 则直接处理
        if($isHtml)
        {
            $generator = new \Picqer\Barcode\BarcodeGeneratorHTML();
            if(is_array($barColor)) $barColor = 'black';
            $html = $generator->getBarcode($text, $generator::TYPE_CODE_128, $width, $height, $barColor);
            if(!$showText) return $html;
            // 如果需要展示文字条码
            return "<div class='lmt-bar-code' style='display:inline-block;text-align:center;'>{$html}<span>{$text}</span></div>";
        }
        // 处理图片
        $path = \think\facade\Config::get("bar_code");
        $fileName = $text . ".png";
        if(!is_dir($path)) mkdir($path, 0777, true);
        $absName = "{$path}{$fileName}";
        // 如果条码存在则直接返回
        if(is_file($absName) && !$replace) return self::hiddenRootPath($absName);
        $generator = new \Picqer\Barcode\BarcodeGeneratorPNG();
        file_put_contents($absName, $generator->getBarcode($text, $barType, $width, $height, $barColor));
        if(!$showText) return self::hiddenRootPath($absName);
        // 如果图片需要展示文字条码
        list($srcW, $srcH) = getimagesize($absName);
        $im = @imagecreatetruecolor($srcW + 10, $srcH + 20);
        $colorWhite = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $colorWhite);
        $textColor = imagecolorallocate($im, 0, 0, 0);
        $toW = $srcW / 2 - (strlen($text) / 2 * 10);
        imagestring($im, 12, $toW, $srcH + 5, $text, $textColor);
        $resource = imagecreatefrompng($absName);
        imagecopyresized($im, $resource,5,3,0,0,$srcW,$srcH ,imagesx($resource),imagesy($resource));
        imagepng($im, $absName);
        imagedestroy($im);
        imagedestroy($resource);
        return self::hiddenRootPath($absName);
    }

    /**
     * html 转 pdf
     * @param string $html HTML
     * @param string $path 输出路径
     * @param string $filename 文件名
     * @param array $pageSize PDF尺寸，默认为 A4
     * @return false|string 成功返回文件路径，失败返回 false
     * @throws \Mpdf\MpdfException
     */
    public function HTML2PDF($html, $path, $filename = '', $pageSize = [])
    {
        if(empty($html) || empty($path)) return false;
        if(empty($filename)) $filename = Tools::getRandStr(16). ".pdf";
        if(!Tools::endWith($filename, "pdf", false)) $filename .= ".pdf";
        if(!Tools::endWith($path, '/')) $path .= '/';
        if(!is_dir($path)) mkdir($path, 0777, true);
        if(empty($pageSize)) $pageSize = '';
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'UTF-8',
            'format' => $pageSize,
            'default_font' => '',
            'margin_left' => 6,
            'margin_right' => 6,
            'margin_top' => 2,
            'margin_bottom' => 0,
        ]);
        //设置中文字体--乱码解决
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;
        $mpdf->WriteHTML($html);
        $output = "{$path}{$filename}";
        $mpdf->Output($output);
        return $output;
    }
}